package nacos

import (
	"fmt"
	"time"

	"gitee.com/zawei/yggdrasil/pkg/config/source"
	"gitee.com/zawei/yggdrasil/pkg/utils/xstrings"
	"github.com/nacos-group/nacos-sdk-go/clients/config_client"
	"github.com/nacos-group/nacos-sdk-go/vo"
)

type nacosSource struct {
	item   *item
	client config_client.IConfigClient
}

func (n *nacosSource) Read() (*source.ChangeSet, error) {
	content, err := n.client.GetConfig(vo.ConfigParam{
		DataId: n.item.DataID,
		Group:  n.item.Group,
	})
	if err != nil {
		return nil, fmt.Errorf("fault to get config (dataID: %s, groupName: %s): %s", n.item.DataID, n.item.Group, err.Error())
	}
	cs := &source.ChangeSet{
		Priority:  source.PriorityRemote,
		Timestamp: time.Now(),
		Source:    n.String(),
		Data:      xstrings.Str2bytes(content),
		Format:    n.item.Format,
	}
	cs.Checksum = cs.Sum()
	return cs, nil
}

func (n *nacosSource) Watch() (source.Watcher, error) {
	return newWatcher(n.client, n.String(), n.item)
}

func (n *nacosSource) String() string {
	return "nacos"
}
